import React, { useCallback, useState } from 'react'
import { Button, Modal, Form, Input, message } from 'antd';
import { getLogin } from '@/api';
import { useNavigate } from 'react-router-dom';
import _ from "lodash"

function Login() {
  // 默认开启窗口
  const [isModalOpen, setIsModalOpen] = useState(true);
  // 实例化
  const navigate = useNavigate()

  // 登录事件
  // 用loadsh实现防抖功能
  const onFinish = useCallback(_.debounce((values) => {
    // console.log(values, "*************")
    getLogin(values).then(res => {
      console.log(res)
      if (res.code === 1) {
        message.success(res.msg)
        // 登录成功token存入本地,refreshToken存入本地
        localStorage.setItem('token', res.token)
        localStorage.setItem('refreshToken', res.refreshToken)
        // 2秒后跳转至主页面
        setTimeout(() => {
          navigate('/home/zhineng')
        }, 1500);
      } else {
        message.error(res.msg)
      }
    })
  }, 2000))

  return (
    <div className='loginPage'>
      <Modal title="登录页" open={isModalOpen} footer={null} closeIcon={false}
        style={{
          top: "10rem", //调整浮层位置
          left: "22rem"
        }}>
        <Form
          name="basic"
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 16,
          }}
          style={{
            maxWidth: 600,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            label="账号"
            name="username"
            rules={[
              {
                required: true,
                message: '请输入账号!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: '请输入密码!',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 10,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit">登录</Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Login
